package com.imooc.coupon.vo;

import com.imooc.coupon.constant.CouponStatus;
import com.imooc.coupon.constant.PeriodType;
import com.imooc.coupon.entity.Coupon;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Date 2021/11/12 14:41
 * @Author wangshbv
 * @Description 根据优惠券状态进行分类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CouponClassify {
    //可用的
    private List<Coupon> usable;
    //已经使用的
    private List<Coupon> used;
    //过期的
    private List<Coupon> expired;


    public static CouponClassify classify(List<Coupon> coupons) {
        List<Coupon> usable = new ArrayList<>(coupons.size());
        List<Coupon> used = new ArrayList<>(coupons.size());
        List<Coupon> expired = new ArrayList<>(coupons.size());
        coupons.forEach(c -> {
            //判断优惠券是否过期
            Boolean isExpire = null;
            Long curTime = System.currentTimeMillis();
            if (c.getTemplateSDK().getRule().getExpiration().getPeriod().
                    equals(PeriodType.REGULAR.getCode())) {
                isExpire = c.getTemplateSDK().getRule().getExpiration().getDeadLine() <= curTime;
            } else {
                isExpire = DateUtils.addDays(c.getAssignTime(),
                        c.getTemplateSDK().getRule().getExpiration().getGap()).getTime() <= curTime;
            }
            if (c.getStatus() == CouponStatus.USED) {
                used.add(c);
            } else if (c.getStatus() == CouponStatus.EXPIRED || isExpire) {
                expired.add(c);
            } else {
                usable.add(c);
            }
        });
        return new CouponClassify(usable, used, expired);
    }
}
